package com.atguigu.tingshu.common.kafka.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Kafka 生产者配置类
 */
@Slf4j
@Configuration
public class KafkaProducerConfig {

    @Value("${spring.kafka.bootstrap-servers:localhost:9092}")
    private String bootstrapServers;

    @Value("${spring.kafka.producer.acks:all}")
    private String acks;

    @Value("${spring.kafka.producer.retries:3}")
    private Integer retries;

    @Value("${spring.kafka.producer.batch-size:16384}")
    private Integer batchSize;

    @Value("${spring.kafka.producer.buffer-memory:33554432}")
    private Long bufferMemory;

    /**
     * 生产者配置
     */
    @Bean
    public Map<String, Object> producerConfigs() {
        Map<String, Object> props = new HashMap<>();
        // Kafka 服务器地址
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        // 消息确认机制：all 表示所有副本都确认后才算发送成功
        props.put(ProducerConfig.ACKS_CONFIG, acks);
        // 发送失败重试次数
        props.put(ProducerConfig.RETRIES_CONFIG, retries);
        // 批量发送大小
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, batchSize);
        // 缓冲区大小
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, bufferMemory);
        // 键序列化器
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        // 值序列化器
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        // 请求超时时间
        props.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, 30000);
        // 元数据最大等待时间
        props.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, 60000);
        // 启用幂等性（防止消息重复）
        props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
        // 压缩类型
        props.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy");

        log.info("Kafka 生产者配置初始化完成 - BootstrapServers: {}, Acks: {}", bootstrapServers, acks);
        return props;
    }

    /**
     * 生产者工厂
     */
    @Bean
    public ProducerFactory<String, String> producerFactory() {
        return new DefaultKafkaProducerFactory<>(producerConfigs());
    }

    /**
     * KafkaTemplate 配置
     */
    @Bean
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }

}

